package com.tsq.intelligence.provider.utils;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

public class MusicUtil {
    public static final String FURL = "http://tingapi.ting.baidu.com/v1/restserver/ting?";

    public static final int MAXCOUNT = 5;

    /**
     * 获取songId
     * @param value
     * @return
     */
    public static JSONObject searchMusic(String value) {
        String requestUrl = FURL+"method=baidu.ting.search.catalogSug&query="+value;
        String reUrl = doGet(requestUrl);
        JSONObject reUrlObj = JSONObject.parseObject(reUrl);

        JSONObject reUrlObjData = reUrlObj(reUrlObj,requestUrl);
        JSONObject data = new JSONObject();
        if(null != reUrlObjData.getString("errno")){
            data.put("msg","搜索失败，请稍后再试！");
            data.put("code",0);
            return data;
        }
        String songId= reUrlObjData.getJSONArray("song").getJSONObject(0).getString("songid");
        data.put("msg",songId);
        data.put("code",1);
        return data;
    }

    /**
     * 根据songId获取歌曲播放路径
     * @param songId
     * @return
     */
    public static String searchMusicId(String songId) {
        String reSongUrl = FURL+"method=baidu.ting.song.play&songid="+songId;
        String reSongUrlData = doGet(reSongUrl);
        JSONObject reSongUrlObj= JSONObject.parseObject(reSongUrlData);

        String musicUrl = JSONObject.parseObject(reSongUrlData).getJSONObject("bitrate").getString("show_link");
        return musicUrl;
    }



    /**
     * 发送get请求
     * @return
     */
    private static String doGet(String requestUrl) {
        InputStream inputStream;
        String result = "";
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            inputStream = httpUrlConn.getInputStream();
            result = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 处理首次请求有可能返回错误的方法
     * @param reUrlObj
     * @param requestUrl
     * @return
     */
    private static JSONObject reUrlObj(JSONObject reUrlObj,String requestUrl){
        int currentCount=0;
        String reUrl;
        if(null != reUrlObj.get("errno")){
            while(currentCount < MAXCOUNT){
                reUrl = doGet(requestUrl);
                reUrlObj= JSONObject.parseObject(reUrl);
                if(null == reUrlObj.get("errno")){
                    currentCount = 6;
                }
                currentCount++;
            }
        }
        return reUrlObj;
    }


    public static void main(String[] args) {
        JSONObject jsonObject = searchMusic("天下");
        String music = searchMusicId(jsonObject.getString("msg"));
        System.out.println(music);
    }
}
